import { useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import Alert from 'src/component/Alert';
import BackButton from 'src/component/BackButton';
import Button from 'src/component/Button';
import Form from 'src/component/Form';
import FormInput from 'src/component/FormInput';
import { Severity } from 'src/constant/Notification';
import { Page } from 'src/constant/Page';
import { openSnackbar } from 'src/redux/uiSlice';
import { getResetPwd, emailResend } from 'src/service/userService';
import Bar from "./component/Bar"
import axios from 'axios';
import style from './ForgetPassword.module.scss';

type ForgetPasswordForm = {
  email: string,
  password: string,
  confirmationpassword: string,
  code: string,
}

const ForgetPassword = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [count, setCount] = useState<number>(-1);
  const methods = useForm<ForgetPasswordForm>();
  const formData = useWatch({ control: methods.control });

  useEffect(() => {
    const timer = setInterval(() => {
      setCount(count - 1);
    }, 1000);
    if (count - 1 < 0) {
      setCount(-1);
      clearInterval(timer);
    }

    return () => clearInterval(timer);
  }, [count]);

  const onSubmit = (data: ForgetPasswordForm) => {
    if (data.password !== data.confirmationpassword) {
      methods.setError('confirmationpassword', {}, { shouldFocus: true });

      return;
    }
    getResetPwd({
      uMail: data.email,
      uCode: data.code,
      newPwd: data.password
    }).then(res => {
      if (res.success) {
        navigate(Page.SignIn);
        dispatch(openSnackbar({ message: "修改成功" }));
      } else {
        dispatch(openSnackbar({ message: res.message, severity: 'alert' }));
      }

    }).catch(e => {
      dispatch(openSnackbar({ message: e, severity: 'alert' }));
    })

  };

  const getVerificationCode = () => {
    if (formData.email === undefined || formData.email?.length === 0) {
      methods.setError('email', {}, { shouldFocus: true });

      return;
    }
    emailResend({
      uMail: formData.email
    }).then(() => {
      setCount(30);
      dispatch(openSnackbar({ message: "我们已将Email验证码寄到您的信箱" }));
    }).catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
    // dispatch(startWaiting())
    // axios({
    //   url: `http://206.238.42.24:998/api/User/getSendMail?uMail=${formData.email}`,
    //   method: "post"
    // }).then(res => {
    //   dispatch(finishWaiting())
    //   setCount(30);
    //   if (!res?.data?.message) {
    //     dispatch(openSnackbar({ message: res?.data?.message, severity: 'alert' }))
    //   }
    // })
  };

  return (
    <>
      <Bar />
      <div className={style.self}>
        <BackButton label="登录" navigateToPath={Page.SignIn} />
        <Form methods={methods} onSubmit={onSubmit}>
          <div className={style.accountInput}>
            <FormInput
              label="注册的 Email 地址"
              type="email"
              name="email"
              placeholder="帐号"
              asterisked
              required
            />
            <div className={style.getCodeButton}>
              <Button
                appearance="text"
                onClick={getVerificationCode}
                type="button"
                disabled={count > 0}
              >
                {count > 0 ? count : "取得验证码"}
              </Button>
            </div>
          </div>
          <div className={style.input}>
            <FormInput
              label="Email 验证码"
              type="text"
              name="code"
              placeholder="Email 验证码"
              asterisked
              required
            />
          </div>
          <Alert severity={Severity.Error} className={style.notice}>
            重置登入密码后24小时内禁止提领。
          </Alert>
          <div className={style.input}>
            <FormInput
              label="密码"
              type="password"
              name="password"
              placeholder="你的新密码"
              asterisked
              required
            />
          </div>
          <div className={style.input}>
            <FormInput
              name="confirmationpassword"
              label="确认密码"
              type="password"
              placeholder="请再次输入新密码"
              asterisked
              required
            />
          </div>
          <div className={style.submitButton}>
            <Button size="large" type="submit">
              确认
            </Button>
          </div>
        </Form>
      </div>
    </>
  );
};

export default ForgetPassword;
